package main

import (
	"fmt"
	"github.com/gorilla/websocket"
	"jms/api"
	"jms/initialize"
	"log"
	"net/http"
)

// CorsMiddleware 封装跨域中间件
// 处理 WebSocket 连接
var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		return true // 允许所有来源的连接，生产环境中应进行更严格的检查
	},
}

var channelArr = map[string]string{}

// 处理 WebSocket 连接
func handleWebSocketConnections(w http.ResponseWriter, r *http.Request) {
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println("无法升级到 WebSocket:", err)
		return
	}
	defer conn.Close()

	for {
		channel := r.FormValue("channel")
		ip := r.RemoteAddr
		if ip == "" {
			ip = r.Header.Get("X-Forwarded-For")
			if ip == "" {
				ip = r.Header.Get("X-Real-IP")
			}
		}

		ua := r.Header.Get("User-Agent")
		messageType, message, err := conn.ReadMessage()
		if err != nil {
			//同步消息
			go api.PostTimePage(channelArr[channel], ip, ua)
			break
		}

		channelArr[channel] = string(message)
		fmt.Println("message", channelArr[channel])
		// 回显消息给客户端
		if err := conn.WriteMessage(messageType, message); err != nil {
			break
		}
	}
}

func main() {
	var c = make(chan struct{})
	initialize.InitLog()
	initialize.InitConfig()
	initialize.InitMysql()
	//3.初始化routers
	//router := initialize.InitRouter()

	//初始化翻译器
	if err := initialize.InitTrans("zh"); err != nil {
		panic(err)
	}

	// 添加 WebSocket 路由
	http.HandleFunc("/socket", handleWebSocketConnections)

	// 启动 HTTP 服务器
	go func() {
		if err := http.ListenAndServe(":8076", nil); err != nil {
			log.Fatal("无法启动 WebSocket 服务器:", err)
		}
	}()
	<-c

}
